package com.next.androidintentlibrary;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.app.Context;
import ohos.bundle.BundleInfo;
import ohos.bundle.IBundleManager;
import ohos.rpc.RemoteException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class CalculatorIntents {

    private Context context;
    private Intent intent;
    private ArrayList<HashMap<String, Object>> items;
    private IBundleManager bundleManager;

    private CalculatorIntents(Context context)
    {
        this.context = context;
    }

    public static CalculatorIntents from(Context context)
    {
        return new CalculatorIntents(context);
    }

    // TODO: implement for AppIntents, use same code for other common apps.
    public CalculatorIntents openCalculator() throws RemoteException {
        getAllPackageNames();
        intent = new Intent();
        int d = 0;
        if (items.size() >= 1)
        {
            for (int j = 0; j < items.size(); j++)
            {
                String AppName = (String) items.get(j).get("appName");
                // Log.w("Name",""+AppName);
                if (AppName.matches("Calculator"))
                {
                    d = j;
                    break;
                }
            }
            String packageName = (String) items.get(d).get("packageName");
            intent = bundleManager.getLaunchIntentForBundle(packageName);
        }
        return this;
    }

    private void getAllPackageNames() throws RemoteException {
        items = new ArrayList<>();

        List<BundleInfo> bundleInfos;
        bundleManager = context.getBundleManager();
        bundleInfos = bundleManager.getBundleInfos(0);
        for (BundleInfo bi : bundleInfos)
        {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("appName",bi.appInfo.getLabel());
            map.put("packageName", bi.getName());
            items.add(map);
        }
    }

    public Intent build()
    {
        return intent;
    }

    private void startAbility(Intent intent)
    {
        if (!(context instanceof Ability))
        {
            intent.addFlags(Intent.FLAG_ABILITY_NEW_MISSION);
        }
        context.startAbility(intent,0);
    }

    public void show()
    {
        startAbility(build());
    }

}
